﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SSDUTElectricityChargesNotification
{
    public partial class Form1 : Form
    {
        private static string aboutTitle = "关于";
        private static string aboutText = "大车埋土大学车欠件学院电费缴费推送2.0";
        private static string building = "";
        private static string room = "";
        private static bool minimize = false;
        private static bool autorun = false;
        private static string configPath = "";
        private static int developmentModeTimer = 10;
        private static int retryNum = 0;

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        //启动轮训
        private void Init()
        {
            if (!IsAdministrator())
            {
                //MessageBox.Show("本程序需要管理员权限运行！", "权限错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                ProcessStartInfo startInfo = new ProcessStartInfo();
                startInfo.FileName = Application.ExecutablePath.Replace('/', '\\');
                startInfo.Verb = "runas";
                Process.Start(startInfo);

                notifyIcon1.Dispose();
                System.Environment.Exit(0);
            }
            configPath = Application.ExecutablePath.Replace('/', '\\');
            configPath = configPath.Substring(0, configPath.LastIndexOf('\\') + 1) + "SSDUTElectricityChargesNotificationClient.ini";
            LoadConfig();
            if (!minimize)
            {
                this.Opacity = 100;
            }
            query.Start();
            notifyIcon1.ContextMenuStrip.Items.Find("QueryToolStripMenuItem", false)[0].Text = "停止轮训";
            DoCheck();
        }

        //设置开机启动
        private bool SetAutorun(bool enable)
        {
            try
            {
                if (enable)
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;  
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.SetValue("SSDUTElectricityChargesNotificationClient", Application.ExecutablePath.Replace('/', '\\'));
                    R_run.Close();
                    R_local.Close();
                }
                else
                {
                    RegistryKey R_local = Registry.LocalMachine;//RegistryKey R_local = Registry.CurrentUser;  
                    RegistryKey R_run = R_local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    R_run.DeleteValue("SSDUTElectricityChargesNotificationClient", false);
                    R_run.Close();
                    R_local.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("设置启动项失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        //保存设置，启动轮训
        private void SetConfig(string b, string r)
        {
            //保存设置
            bool flag = true;
            building = b;
            room = r;
            flag = flag && INIOperationClass.WriteConfig("config", "building", building, configPath);
            flag = flag && INIOperationClass.WriteConfig("config", "room", room, configPath);
            if (minimize != checkBox2.Checked)
            {
                minimize = checkBox2.Checked;
                flag = flag && INIOperationClass.WriteConfig("config", "minimize", minimize.ToString(), configPath);
            }
            if (autorun != checkBox1.Checked)
            {
                autorun = checkBox1.Checked;
                flag = flag && SetAutorun(autorun);
                flag = flag && INIOperationClass.WriteConfig("config", "autorun", autorun.ToString(), configPath);
            }
            INIOperationClass.WriteConfig("config", "path", Application.ExecutablePath.Replace('/', '\\'), configPath);
            if (!flag)
            {
                MessageBox.Show("保存设置失败", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("保存设置成功", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            DoCheck();
        }

        //读取设置
        private void LoadConfig()
        {
            string temp = "";
            building = INIOperationClass.ReadConfig("config", "building", null, configPath);
            room = INIOperationClass.ReadConfig("config", "room", null, configPath);
            temp = INIOperationClass.ReadConfig("config", "minimize", null, configPath);
            minimize = Boolean.Parse(temp.Equals(String.Empty) ? "false" : temp);
            checkBox2.Checked = minimize;
            temp = INIOperationClass.ReadConfig("config", "autorun", null, configPath);
            autorun = Boolean.Parse(temp.Equals(String.Empty) ? "false" : temp);
            checkBox1.Checked = autorun;
            temp = building.Equals(String.Empty) ? "1" : building;
            comboBox1.SelectedIndex = Int32.Parse(temp) - 1;
            textBox1.Text = room;
        }

        private void DoCheck()
        {
            Thread firstCheck = new Thread(new ThreadStart(QueryTask));
            firstCheck.IsBackground = true;
            firstCheck.Start();
        }

        private void QueryTask()
        {
            try
            {
                string res = GetCharge(building, room);
                if (res != "")
                {
                    //推送
                    MessageBox.Show(building + "舍" + room + "室，已欠电费" + Math.Abs(Double.Parse(res)).ToString() + "元"
                        , "欠费通知", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }catch(Exception ex)
            {
                if(++retryNum<=3)
                {
                    QueryTask();
                }
                else
                {
                    retryNum = 0;
                    MessageBox.Show("Query failed after 3 attempts.\nLast error message: "+ex.Message+"\nAuto query has been stoped.", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    query.Stop();
                    notifyIcon1.ContextMenuStrip.Items.Find("QueryToolStripMenuItem", false)[0].Text = "开始轮训";
                }
                
            }

        }

        //爬取电费，未欠费返回空
        private string GetCharge(string building, string room)
        {
            if (building == "" || room == "")
            {
                return "";
            }
            string flag = room + "</th><td width=\"290px\">";
            string res = "";
            Uri uri = new Uri("http://ssbems.dlut.edu.cn:8080/mcweb/RechargeNotice.aspx?category=8&name=" + building + "%E8%88%8D");
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
            myReq.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0";
            myReq.Accept = "*/*";
            myReq.KeepAlive = true;
            myReq.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
            HttpWebResponse result = (HttpWebResponse)myReq.GetResponse();
            Stream receviceStream = result.GetResponseStream();
            StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
            string strHTML = readerOfStream.ReadToEnd();
            readerOfStream.Close();
            receviceStream.Close();
            result.Close();
            int index = strHTML.IndexOf(flag);
            if (index >= 0)
            {
                res = strHTML.Substring(index + flag.Length);
                res = res.Substring(0, res.IndexOf("<"));
            }
            return res;
        }

        private void ShowAbout()
        {
            MessageBox.Show(aboutText, aboutTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //弹出气泡最小化
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Visible = false;
            e.Cancel = true;
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Opacity = 100;
            this.Visible = true;
        }

        private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Opacity = 100;
            this.Visible = true;
        }

        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowAbout();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            notifyIcon1.Dispose();
            System.Environment.Exit(0);
        }

        private void button1_MouseClick(object sender, MouseEventArgs e)
        {
            ShowAbout();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SetConfig((comboBox1.SelectedIndex + 1).ToString(), textBox1.Text);
        }

        private void DoTick(object sender, EventArgs e)
        {
            DoCheck();
        }

        private static bool IsAdministrator()
        {
            bool result;
            try
            {
                WindowsIdentity identity = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                result = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            catch
            {
                result = false;
            }
            return result;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show(query.Enabled.ToString(), "query", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void checkBox2_MouseClick(object sender, MouseEventArgs e)
        {
            if (--developmentModeTimer == 0)
            {
                this.Height = 220;
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string res = GetCharge(building, room);
            if (res != "")
            {
                //推送
                MessageBox.Show(building + "舍" + room + "室，已欠电费" + Math.Abs(Double.Parse(res)).ToString() + "元"
                   , "欠费通知", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                MessageBox.Show("0", "charge", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void 开始轮训ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if(query.Enabled)
            {
                query.Stop();
                notifyIcon1.ContextMenuStrip.Items.Find("QueryToolStripMenuItem",false)[0].Text = "开始轮训";
            }
            else
            {
                query.Start();
                notifyIcon1.ContextMenuStrip.Items.Find("QueryToolStripMenuItem", false)[0].Text = "停止轮训";
            }
        }
    }
}
